import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDataThread implements Runnable {
	final static int BUFFER_SIZE = 4096;
	
	private int data_port;
	private ServerSocket data_server;
	private Socket data_s;
	private BufferedReader data_in;
	private DataOutputStream data_out;
	private File f;
	
	private MainWindow parent;
	
	private int downloadSize;

	public ServerDataThread(int port, MainWindow mw) {
		// TODO Auto-generated constructor stub
		data_port = port;
		parent = mw;
	}

	@Override
	public void run() {
		data_server = null;
		try {
			data_server = new ServerSocket(data_port);
			System.out.println("Data server created!");
			f = new File(parent.fileName);
			boolean end_flag = false;
			while (!end_flag) {
				data_s = data_server.accept();
				System.out.println("Data server accepted!");
				data_in = new BufferedReader(new InputStreamReader(
						data_s.getInputStream()));
				String line = data_in.readLine();
				System.out.println("Datain:line= " + line);
				String header = line.split(" ")[0];
				System.out.println("Datain:header= " + header);
				int header_code = Integer.parseInt(line.split(" ")[1]);
				System.out.println("Datain:header code= " + header_code);
				if (header.equals("request")) {
					switch (header_code) {
					case 1:
						snd_data();
						break;
					case -1:
						end_flag = true;
						System.out.println("DataServer says: byebye!");
						break;
					}
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			System.out.println("Error: DataServerThread:run");
		}
	}

	private void snd_data() {
		// TODO Auto-generated method stub
		String line;
		//String[] client_inf;
		try {
			System.out.println("begin snd data");
			String client_WifiIP = data_in.readLine();
			//System.out.println("snd data 1");
			//System.out.println("snd data line= " + line);
			// File request format: filename start-frame end-frame
			Client client = MainWindow.clients.get(client_WifiIP);
			int startPosition = client.getStartPosition();
			int endPosition = client.getEndPosition();
			int curPosition = startPosition;
			//System.out.println("snd data 2");
			//response 1
			data_out = new DataOutputStream(data_s.getOutputStream());
			String resp = "response 1\n";
			data_out.writeBytes(resp);
			resp = parent.fileName + " " + startPosition + " " + endPosition + "\n";
			data_out.writeBytes(resp);
			data_out.flush();
			//System.out.println("before fis");
//			// ---debug--- current file path--
//			File curf = new File(".");
//			System.out.println(curf.getAbsolutePath());
//			// -------------------------------
			//System.out.println(f.getAbsolutePath());
			if (f.exists()) {
				//FileInputStream fis = new FileInputStream(f);
				RandomAccessFile fis = new RandomAccessFile(f,"rw");
				fis.seek(startPosition);
				System.out.println("after fis");
				byte[] buf = new byte[BUFFER_SIZE];
				//for (int size = 0; size != -1; size = fis.read(buf)) {
//					data_out.write(buf, 0, size);
//					data_out.flush();
//				}
				downloadSize = 0;
				while (curPosition < endPosition){
					int len = fis.read(buf, 0, BUFFER_SIZE);
					if (len == -1) {  
						break;  
					}  
					data_out.write(buf, 0, len);  
					curPosition = curPosition + len;  
					if (curPosition > endPosition) {  
						downloadSize += len - (curPosition - endPosition) + 1;  
					} else {  
						downloadSize += len;  
					}  
				}
				// s_out.close();
				fis.close();
				data_in.close();
				data_out.close();
				data_s.close();
			} else {
				System.out.println("Error: filename wrong!");
			}
//			client.setDownloadSize(downloadSize);
//			MainWindow.clients.put(client_WifiIP, client);
			System.out.println("snd_data ended! downloadSize = " + downloadSize);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			System.out.println("Error: snd_data: readLine");
		}
	}

}
